<template>
	<div>
		<div class="img-list" v-if="!pattern">
			<div
				:style="imgStyle"
				class="img"
				v-for="(item, index) in showImgsProxy"
				:key="index"
			>
				<div class="img-options">
					<i
						v-if="close"
						class="el-icon-close"
						@click="delImg(index)"
					></i>
					<i
						v-if="enlarge"
						class="el-icon-zoom-in"
						@click="
							currentImg = index
							previewOpen = true
						"
					></i>
				</div>
				<el-image :src="item.src">
					<div slot="error" class="image-slot">
						<i class="el-icon-picture-outline"></i>
						<h1 style="text-align: center">加载失败</h1>
					</div>
				</el-image>
				<!-- <img :style="imgStyle" :src="item.src"> -->
			</div>
			<div
				:style="imgStyle"
				v-if="showImgsProxy.length < imgLength"
				class="img"
				@click="$refs['upFile'].click()"
			>
				<img v-if="btnImg" :src="btnImg" />
				<div v-else class="img-addBtn"></div>
				<input
					@change="selImg"
					ref="upFile"
					type="file"
					accept="image/*"
					style="display: none"
				/>
			</div>
		</div>
		<div
			v-else
			@click="
				currentImg = 0
				previewOpen = true
			"
		>
			<img v-if="btnImg" :style="imgStyle" :src="btnImg" />
			<el-button type="text" v-else-if="btnTxt">{{ btnTxt }}</el-button>
		</div>
		<template v-if="previewOpen">
			<div class="left" @click="leftClick">
				<i
					class="el-icon-arrow-right"
					style="transform: rotateZ(180deg)"
				></i>
			</div>
			<div class="right" @click="rightClick">
				<i class="el-icon-arrow-right"></i>
			</div>
			<div class="top" @click="previewOpen = false">
				<i class="el-icon-circle-close"></i>
			</div>
			<el-dialog :visible.sync="previewOpen">
				<el-image
					v-if="currentImg > -1"
					:src="showImgsProxy[currentImg].src"
				>
					<div slot="placeholder" class="image-slot">
						<i class="el-icon-loading"></i>
						<h1>加载中</h1>
					</div>
					<div slot="error" class="image-slot">
						<i class="el-icon-picture-outline"></i>
						<h1>加载失败</h1>
					</div>
				</el-image>
				<!-- <img v-if="currentImg>-1" :src="showImgs[currentImg].src" /> -->
			</el-dialog>
		</template>
	</div>
</template>
<script>
/**
 * 上传图片组件 @jie
 * v-model 直接绑定
 * 添加/显示 双模式
 * 详细：v-model绑定的是表单数据，是不会直接用于图片展示的。它要有值只会是String并且,相连
 * upimg 有添加和展示两种组件模式，添加模式会有添加的操作按钮，展示则只用于图片展示
 */
import { UploadImage } from '@/api/common/common'
export default {
	name: 'upImg',
	props: {
		//v-model 绑定值
		value: null,
		//适用pattern时绑定图片 作用与v-model的作用差不多 但更语义化
		imgList: String,
		//组件模式 false 上传模式 true 展示模式
		pattern: {
			type: Boolean,
			default: false
		},
		//是否允许放大
		enlarge: {
			type: Boolean,
			default: true
		},
		close: {
			type: Boolean,
			default: true
		},
		// 按钮图片
		btnImg: {
			type: String
		},
		// 按钮文字
		btnTxt: {
			type: String
		},
		// 图片数量
		imgLength: {
			type: Number,
			default: 2
		},
		// 图片宽度
		imgWidth: {
			type: [Number, String],
			default: "auto"
		},
		//图片高度
		imgHeight: {
			type: [Number, String],
			default: "auto"
		}
	},
	data() {
		return {
			showImgs: [],//展示图片
			previewOpen: false, //预览打开
			currentImg: -1, //当前图片
			delImgs: [] //删除的图片
		}
	},
	computed: {
		imgStyle() {
			return {
				width: this.imgWidth,
				height: this.imgHeight,
			}
		},
		showImgsProxy() {
			let arr = [];
			this.showImgs.forEach(v => {
                let p = {...v};
                p.src = p.src.replace(/http:\/\/172.20.0.177:9101\//,'/getpic/')
                arr.push(p);
            })
            return arr;
		}
	},
	watch: {
		showImgs: {
			immediate: true,
			handler() {
				if (this.showImgs.length > 0 && !(this.value)) {
					this.$emit('input', 'Nosubmit');
				} else if (this.showImgs.length === 0 && this.value === 'Nosubmit') {
					this.$emit('input', null);
				}
			}
		},
		//v-model value绑定初始化
		value: {
			immediate: true,
			handler() {
				if (typeof this.value === 'string') {
					if (this.value === 'Nosubmit') return;
					this.value.split(',').forEach(item => {
						if (item) {
							this.showImgs.push({
								src: item
							});
						}
					});
				}
			}
		},
		imgList: {
			immediate: true,
			handler() {
				if (typeof this.imgList === 'string') {
					this.imgList.split(',').forEach(item => {
						if (item) {
							this.showImgs.push({
								src: item
							});
						}
					});
				}
			}
		},
		currentImg() {
			if (this.currentImg !== -1 && !this.showImgs[this.currentImg]) {
				this.$message.warning('未找到图片');
				this.currentImg = -1;
				this.previewOpen = false;
			}
		}
	},
	methods: {
		//大图左右切换
		leftClick() {
			if (this.currentImg > 0) {
				this.currentImg--;
			}
		},
		rightClick() {
			if (this.currentImg < this.showImgs.length - 1) {
				this.currentImg++;
			}
		},

		delImg(index) {
			let showImgs = this.showImgs;
			if (!(showImgs[index].file)) {
				//没有file说明并不是 new file
				this.delImgs.push(showImgs[index].src);
			}
			showImgs.splice(index, 1);
		},
		// 文件上传点击确定
		selImg() {
			let that = this;
			let file = this.$refs['upFile'].files[0];
			let reads = new FileReader();
			reads.readAsDataURL(file)
			reads.onload = function (e) {
				that.showImgs.push({
					src: this.result, // src base64 图片展示格式
					file: file // formData 文件
				});
			};
			this.$refs['upFile'].value = "";
		},
		getImage(src) {
			// //必须保证src为网络路径
			// let src = src.replace('http://172.20.0.177:9101/','/imgApi');
			// axios.get(src, { responseType: "arraybuffer" })
			//     .then(response => {
			//         return (
			//             "data:image/png;base64," +
			//             btoa(
			//                 new Uint8Array(response.data).reduce(
			//                     (data, byte) => data + String.fromCharCode(byte),
			//                     ""
			//                 )
			//             )
			//         );
			//     })
			//     .then(data => {
			//         this.imgUrl = data; //赋值给img标签的src属性
			//     });
		},
		//submit
		submit() {
			if (this.pattern) { return false; }
			let formData = new FormData(); // imgs文件
			let imgs = []; //imgs 中保存的是 图片的网络路径
			let filesIndex = [];
			for (let i = 0; i < this.showImgs.length; i++) {
				let item = this.showImgs[i];
				if (item.file) {
					formData.append('file', item.file);
					filesIndex.push(i);
				} else {
					imgs.push(item.src); //没有file代表 网络图片
				}
			}
			let prom = new Promise((resolve, reject) => {
				if (formData.getAll('file').length) {
					UploadImage(formData).then(res => {
						let data = res.data;
						if (!data) {
							reject(res.msg);
						}
						data.forEach(item => {
							imgs.push(item.filePth);
						});
						filesIndex.forEach(item => {
							this.showImgs.splice(item, 1);
						});
                        this.$emit('input', imgs.join(','));
						resolve();
					}).catch(msg => {
						this.$message.warning(msg);
						reject(msg);
					});
				} else {
					this.$emit('input', imgs.join(','));
					resolve();
				}
			});
			return prom;
		}
	}
}
</script>
<style scoped>
.el-image {
	height: 100%;
}

>>> .el-dialog__body .el-image {
	display: flex;
	justify-content: center;
	align-items: center;
}

>>> .el-dialog__body .el-image > .el-image__inner {
	width: 100%;
	height: auto;
	max-height: 100%;
}

>>> .image-slot {
	margin-top: 10%;
	text-align: center;
}

.image-slot > * {
	height: 100%;
	font-size: 1rem;
	color: white;
}

.image-slot > h1 {
	margin-top: 0.1rem;
	font-size: 0.2rem !important;
}

.left,
.right,
.top {
	height: 0.6rem;
	width: 0.6rem;
	font-size: 0.3rem;
	text-align: center;
	line-height: 0.6rem;
	color: white;
	z-index: 9999;
	position: fixed;
	top: calc(50% - 0.3rem);
	background-color: #666;
	border-radius: 50%;
}

.left {
	left: 1rem;
}

.right {
	right: 1rem;
}

.top {
	cursor: pointer;
	top: 0.3rem;
	right: 1rem;
	font-size: 0.6rem;
	background-color: transparent;
}

>>> .el-dialog {
	width: auto;
	max-width: 80%;
	height: 80%;
	border-radius: 0px;
	background-color: transparent;
	box-shadow: none;
}

>>> .el-dialog__header {
	display: none;
}

>>> .el-dialog .el-dialog__body {
	padding: 0px !important;
	height: 100%;
	text-align: center;
}

>>> .el-dialog__body {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 10rem;
}

>>> .el-dialog__body img {
	height: 100%;
}

.img {
	position: relative;
}

/* 第二个开始 left 10px */
.img:not(:first-child) {
	margin-left: 10px;
}

.el-icon-close {
	margin-right: 0.2rem;
}

.img-options {
	position: absolute;
	top: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.4);
	color: white;
	display: none;
	align-items: center;
	justify-content: center;
	font-size: 0.4rem;
	cursor: pointer;
	z-index: 99;
}

.img:hover > .img-options {
	display: flex;
}

.img > * {
	border: 1px solid #dcdfe6;
	width: 100%;
	height: 100%;
	border-radius: 4px;
}

.img > *:hover {
	border-color: #c0c4cc;
}

.img-list {
	display: flex;
}

.img-addBtn {
	display: flex;
	align-items: center;
	justify-content: center;
}

.img-addBtn:hover::after,
.img-addBtn:hover::before {
	background-color: #c0c4cc;
}

.img-addBtn::after {
	content: '';
	display: block;
	background-color: #dcdfe6;
	position: absolute;
	width: 1px;
	height: 0.75rem;
}

.img-addBtn::before {
	content: '';
	display: block;
	background-color: #dcdfe6;
	position: absolute;
	width: 0.75rem;
	height: 1px;
}
</style>
